﻿using FreeSwitch.EventSocket.Parser;
using Xunit;

namespace FreeSwitch.EventSocket.Tests.Parser
{
	public class StringBufferTest
	{
		private readonly StringBuffer _buffer = new StringBuffer(16);

		[Fact]
		void AppendOnce()
		{
			_buffer.Append("123".ToCharArray());
			Assert.Equal("123", GetString());
		}

		[Fact]
		void AppendTwice()
		{
			_buffer.Append("123".ToCharArray());
			_buffer.Append("345".ToCharArray());
			Assert.Equal("123345", GetString());
		}

		[Fact]
		void AppendAutoSize()
		{
			_buffer.AutoGrow = true;
			_buffer.Append("1234567890".ToCharArray());
			Assert.Equal(16, _buffer.Capacity);
			_buffer.Append("1234567890".ToCharArray());
			Assert.Equal(32, _buffer.Capacity);

			Assert.Equal("12345678901234567890", GetString());
		}

		[Fact]
		void SimplePop()
		{
			_buffer.Append("123345".ToCharArray());

			char[] tmp = new char[3];
			_buffer.Pop(tmp, 0, 2);
			Assert.Equal("12", new string(tmp));
			Assert.Equal("3345", GetString());
		}

		[Fact]
		void PopAppendPop()
		{
			_buffer.Append("123345".ToCharArray());

			char[] tmp = new char[20];
			_buffer.Pop(tmp, 0, 2);
			Assert.Equal("12", new string(tmp));
			Assert.Equal("3345", GetString());

			_buffer.Append("678".ToCharArray());

			_buffer.Pop(tmp, 0, 5);
			Assert.Equal("33456", new string(tmp));
			Assert.Equal("78", GetString());

		}

		[Fact]
		void ReadLine()
		{
			_buffer.AutoGrow = true;
			_buffer.Append("Content-Type: api/reply\nResponse-Text: +OK\n\n".ToCharArray());
			Assert.Equal("Content-Type: api/reply", _buffer.ReadLine());
			Assert.Equal("Response-Text: +OK", _buffer.ReadLine());
		}

		string GetString()
		{
			char[] value = new char[_buffer.Count];
			_buffer.CopyTo(value, 0, _buffer.Count);
			return new string(value);
		}

	}
}
